package com.sctvcloud.renhe.ui.activities;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.view.View;

import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.base.BaseActivity;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.beans.FUsers;
import com.sctvcloud.renhe.beans.SerialThirdInfo;
import com.sctvcloud.renhe.beans.SingleResult;
import com.sctvcloud.renhe.http.AbsNetCallBack;
import com.sctvcloud.renhe.http.DMethods;
import com.sctvcloud.renhe.http.NetUtils;
import com.sctvcloud.renhe.ui.utils.TitleUtils;
import com.sctvcloud.renhe.utils.UserManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 绑定手机号
 */
public class BindPhoneActivity extends BaseActivity {

    private final int WHAT_TIMW = 901;
    private final int WHAT_TIMW_STOP = 902;

    public static final String EX_THIRD = "ex_third";

    private final int Time_Count = 60;

    @BindView(R.id.login_et_phone)
    protected CustomFontEditText etPhone;
    @BindView(R.id.login_et_code)
    protected CustomFontEditText etCode;
    @BindView(R.id.login_btn_code)
    protected CustomFontTextView btnCode;
    @BindView(R.id.login_btn_login)
    protected CustomFontTextView btnLogin;

    private Handler handler;
    private int time;

    private SerialThirdInfo thirdInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        thirdInfo = (SerialThirdInfo) getIntent().getSerializableExtra(EX_THIRD);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg != null) {
                    parseMsg(msg);
                }
            }
        };
        if (thirdInfo == null) {
            toast("错误的第三方登录信息");
            finish();
        }
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_bind_phone);
        ButterKnife.bind(this);
    }

    @OnClick(value = {R.id.login_btn_code, R.id.login_btn_login, R.id.login_img_back})
    public void loginClick(View v) {
        switch (v.getId()) {
            case R.id.login_btn_code:
                if (checkPhone()) {
                    getCode();
                }
                break;
            case R.id.login_btn_login:
                if (checkPhone() && checkCode()) {
                    login();
                }
                break;
            case R.id.login_img_back:
                finish();
                break;
        }
    }

    private boolean checkPhone() {
        if (TextUtils.isEmpty(etPhone.getText().toString()) || !etPhone.getText().toString().matches(Constances.MATCHER_PHONE)) {
            toast(R.string.please_input_valued_phone);
            return false;
        }
        return true;
    }

    private boolean checkCode() {
        if (TextUtils.isEmpty(etCode.getText().toString())) {
            toast(R.string.please_input_code);
            return false;
        }
        return true;
    }

    private synchronized void getCode() {
        btnCode.setEnabled(false);
        ArrayMap<String, Object> p = new ArrayMap<>();
        p.put("phoneNumber", etPhone.getText().toString());
        NetUtils.getNetAdapter().postGetSingle(getOwnerName(), DMethods.AuthCode, p, new AbsNetCallBack<SingleResult>(null) {
            @Override
            public void onSuc(SingleResult s) {
                time = 0;
                handler.sendEmptyMessageDelayed(WHAT_TIMW, 1000);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                toast(R.string.get_verification_failed);
//                if (TextUtils.isEmpty(errorMsg)) {
//                } else {
//                    toast(errorMsg);
//                }
                btnCode.setEnabled(true);

            }
        });
    }

    private synchronized void login() {
        btnLogin.setEnabled(false);
        showProgress("正在登录中...");
        ArrayMap<String, Object> para = new ArrayMap<>();
        para.put("isOpenLogin", true);
        para.put("openAvatar", thirdInfo.getOpenAvatar());
        para.put("openId", thirdInfo.getOpenId());
        para.put("openName", thirdInfo.getOpenName());
        para.put("openType", thirdInfo.getOpenType());
        para.put("authCode", etCode.getText().toString());
        para.put("phoneNumber", etPhone.getText().toString());
        NetUtils.getNetAdapter().postLogin(getOwnerName(), para, new AbsNetCallBack<FUsers>(null) {
            @Override
            public void onSuc(FUsers fUsers) {
                if (fUsers != null) {
                    btnLogin.setEnabled(true);
                    toast(R.string.login_suc);
                    if (TextUtils.isEmpty(fUsers.getAvatar())) {
                        if (!TextUtils.isEmpty(thirdInfo.getOpenAvatar())) {
                            fUsers.setAvatar(thirdInfo.getOpenAvatar());
                        }
                    }
                    fUsers.setBindType(thirdInfo.getOpenType());
                    UserManager.getInstance().setUser(BindPhoneActivity.this, fUsers);
                    closeProgress();
                    setResult(RESULT_OK);
                    finish();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                btnLogin.setEnabled(true);
                closeProgress();
                toast(R.string.bind_phone_failed);
            }

            @Override
            public FUsers doInBackground(FUsers fUsers) {
//                if (fUsers==null){
//                    fUsers=new FUsers();
//                    fUsers.setUserId("sie231235254");
//                    fUsers.setUserName("测试");
//                }
                return super.doInBackground(fUsers);
            }
        });
    }

    private void parseMsg(Message msg) {
        int what = msg.what;
        if (what == WHAT_TIMW) {
            handler.removeMessages(WHAT_TIMW);
            time++;
            if (time > Time_Count) {
                btnCode.setText(R.string.get_agin);
                btnCode.setEnabled(true);
            } else {
                handler.sendEmptyMessageDelayed(WHAT_TIMW, 1000);
                btnCode.setText(String.format(getString(R.string.has_send_s), time));
            }
        } else if (what == WHAT_TIMW_STOP) {
            handler.removeMessages(WHAT_TIMW);
            btnCode.setEnabled(true);
        }
    }
}
